<?
	// Funktion die dazu entwickelt wurde alle Kunden die bereits     
	// in der Kundendatenbank vorhanden sind zu geocodieren           
	////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////
	
	// Verbindungsdaten
	$username="root";
	$password="";
	$database="my_pffm";
	
	// MAX_ECEXUTION_TIME setzen
	ini_set('max_execution_time','60000');
	
	// Google Maps HOST 
	define("MAPS_HOST", "maps.google.com");
	
	// Google Maps API-KEY
	define("KEY", "ABQIAAAA8RIsqO5oxmBN0WDmelemhhTpuw8121_BFbh5Vg4xr-5HADDyFRSxSdJEYC3rxJAO2I-8hIX5tUd1vw");
	
	// Datenbankverbindung herstellen
	$connection = mysql_connect("localhost", $username, $password);
	if (!$connection) {
	  die("Verbindung konnte nicht Hergestellt werden : " . mysql_error());
	}
	
	// Datenbank auswählen
	$db_selected = mysql_select_db($database, $connection);
	if (!$db_selected) {
	  die("Datenbank konnte nicht selektiert werden : " . mysql_error());
	}
	
	// Alle Datensätze selektieren
	$query = "SELECT * FROM kunden WHERE 1";
	
	// Anfrage ausführen
	$result = mysql_query($query);
	if (!$result) {
	  die("Es ist ein Fehler aufgetreten: " . mysql_error());
	}
	
	// Verzögerung
	$delay = 0;
	$base_url = "http://" . MAPS_HOST . "/maps/geo?output=xml" . "&key=" . KEY;
	
	// Adresse einzeln durchlaufen
	while ($row = @mysql_fetch_assoc($result)) {
	  $geocode_pending = true;
	
	  while ($geocode_pending) {
		$address = utf8_decode($row["k_ort"]). "," .utf8_decode($row['k_strasse']);
		$id = $row["k_id"];
		$request_url = $base_url . "&q=" . urlencode($address);
		$xml = simplexml_load_file($request_url) or die("url not loading");
	
		$status = $xml->Response->Status->code;
		if (strcmp($status, "200") == 0) {
		  // Successful geocode
		  $geocode_pending = false;
		  $coordinates = $xml->Response->Placemark->Point->coordinates;
		  $coordinatesSplit = explode(",",$coordinates);
		  // Format: Longitude, Latitude, Altitude
	
		  $k_geoX = $coordinatesSplit[0];
		  $k_geoY = $coordinatesSplit[1];
		  
	
		  $query = sprintf("UPDATE kunden " .
				 " SET k_geoX = '$k_geoX', k_geoY = '$k_geoY' " .
				 " WHERE k_id = '$id' LIMIT 1;",
				 mysql_real_escape_string($k_geoX),
				 mysql_real_escape_string($k_geoY),
				 mysql_real_escape_string($id));
		  $update_result = mysql_query($query);
		  if (!$update_result) {
			die("Invalid query: " . mysql_error());
		  }
		} else if (strcmp($status, "620") == 0) {
		  // sent geocodes too fast
		  $delay += 100000;
		} else {
		  // failure to geocode
		  $geocode_pending = false;
		  echo "Address " . $address . " failed to geocoded. ";
		  echo "Received status " . $status . "\n";
		}
		usleep($delay);
	  }
	}
?>
